// 接口类型定义
export interface RegisterParams {
  email: string
  verification_code: string
  name: string
  password: string
}

export interface RegisterResponse {
  access_token: string
  token_type: string
  expires_in: number
}

export interface ApiResponse<T = any> {
  success: boolean
  code: number
  message: string
  type: string
  data?: T
}

// API 配置
const API_BASE_URL = 'http://192.168.0.31:8083/api/v1'

// 注册接口
export const registerUser = async (params: RegisterParams): Promise<ApiResponse<RegisterResponse>> => {
  try {
    const formData = new FormData()
    formData.append('email', params.email)
    formData.append('verification_code', params.verification_code)
    formData.append('name', params.name)
    formData.append('password', params.password)

    const response = await fetch(`${API_BASE_URL}/register`, {
      method: 'POST',
      body: formData,
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result: ApiResponse<RegisterResponse> = await response.json()
    return result
  } catch (error) {
    console.error('Register API failed:', error)
    throw error
  }
}

// 发送验证码接口
export const sendVerificationCode = async (email: string): Promise<ApiResponse> => {
  try {
    const formData = new FormData()
    formData.append('email', email)

    const response = await fetch(`${API_BASE_URL}/send-verification-code`, {
      method: 'POST',
      body: formData,
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result: ApiResponse = await response.json()
    return result
  } catch (error) {
    console.error('Send verification code API failed:', error)
    throw error
  }
}

// Token 管理工具函数
export const saveAuthToken = (data: RegisterResponse) => {
  localStorage.setItem('access_token', data.access_token)
  localStorage.setItem('token_type', data.token_type)
  localStorage.setItem('expires_in', data.expires_in.toString())
  localStorage.setItem('login_time', Date.now().toString())
}

export const getAuthToken = (): string | null => {
  return localStorage.getItem('access_token')
}

export const clearAuthToken = () => {
  localStorage.removeItem('access_token')
  localStorage.removeItem('token_type')
  localStorage.removeItem('expires_in')
  localStorage.removeItem('login_time')
}

export const isTokenExpired = (): boolean => {
  const expiresIn = localStorage.getItem('expires_in')
  const loginTime = localStorage.getItem('login_time')

  if (!expiresIn || !loginTime) return true

  const expirationTime = parseInt(loginTime) + (parseInt(expiresIn) * 1000)
  return Date.now() > expirationTime
}
